package com.xky.ui.module.salesManagement.select;

import com.xky.pojo.SalesShipments;
import com.xky.ui.main.MainView;
import com.xky.ui.module.salesManagement.SalesShipmentsManagement;

import javax.swing.*;
import javax.swing.border.EmptyBorder;
import javax.swing.border.TitledBorder;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 销售发货单高级查询对话框
 */
public class AdvancedSearchSalesShipmentDialog extends JDialog {

    // 日期格式化器
    private static final DateTimeFormatter DATE_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd");
    
    // 界面颜色
    private static final Color BACKGROUND_COLOR = new Color(240, 248, 255);
    private static final Color HEADER_COLOR = new Color(79, 129, 189);
    private static final Color BUTTON_COLOR = new Color(65, 131, 196);
    private static final Color SEARCH_BUTTON_COLOR = new Color(46, 204, 113);
    private static final Color RESET_BUTTON_COLOR = new Color(231, 76, 60);
    
    // 界面组件
    private JTextField shipmentIdField;
    private JTextField shipmentNumberField;
    private JTextField orderIdField;
    private JTextField warehouseIdField;
    private JTextField startDateField;
    private JTextField endDateField;
    private JTextField carrierField;
    private JTextField trackingNumberField;
    private JComboBox<String> shippingMethodCombo;
    private JComboBox<String> statusCombo;
    private JTextField notesField;
    private JTable resultTable;
    private DefaultTableModel tableModel;
    private JButton selectButton;
    private JButton cancelButton;
    
    // 数据相关
    private JTable mainTable;
    private boolean confirmed = false;
    private SalesShipments selectedShipment;

    /**
     * 构造函数
     * @param owner 父窗口
     * @param mainTable 主表格（结果将更新到此表格）
     */
    public AdvancedSearchSalesShipmentDialog(Window owner, JTable mainTable) {
        super(owner, "查询销售发货单", ModalityType.APPLICATION_MODAL);
        this.mainTable = mainTable;
        initUI();
    }
    
    /**
     * 初始化界面
     */
    private void initUI() {
        // 设置窗口属性
        setSize(900, 650);
        setLocationRelativeTo(null);
        setResizable(false);
        
        // 主面板
        JPanel mainPanel = new JPanel(new BorderLayout());
        mainPanel.setBackground(BACKGROUND_COLOR);
        mainPanel.setBorder(new EmptyBorder(15, 15, 15, 15));
        
        // 顶部查询面板
        JPanel searchPanel = createSearchPanel();
        
        // 中间表格面板
        JScrollPane tableScrollPane = createTablePanel();
        
        // 底部按钮面板
        JPanel buttonPanel = createButtonPanel();
        
        // 组装界面
        mainPanel.add(searchPanel, BorderLayout.NORTH);
        mainPanel.add(tableScrollPane, BorderLayout.CENTER);
        mainPanel.add(buttonPanel, BorderLayout.SOUTH);
        
        setContentPane(mainPanel);
    }
    
    /**
     * 创建查询面板
     */
    private JPanel createSearchPanel() {
        JPanel panel = new JPanel(new BorderLayout(0, 10));
        panel.setOpaque(false);
        panel.setBorder(new EmptyBorder(0, 0, 10, 0));
        
        // 创建表单面板
        JPanel formPanel = new JPanel(new GridBagLayout());
        formPanel.setOpaque(false);
        formPanel.setBorder(BorderFactory.createTitledBorder(
            BorderFactory.createLineBorder(HEADER_COLOR), 
            "查询条件", 
            TitledBorder.LEFT, 
            TitledBorder.TOP, 
            new Font("微软雅黑", Font.BOLD, 14), 
            HEADER_COLOR
        ));
        
        GridBagConstraints gbc = new GridBagConstraints();
        gbc.fill = GridBagConstraints.HORIZONTAL;
        gbc.insets = new Insets(5, 10, 5, 10);
        
        // 第一行
        gbc.gridx = 0;
        gbc.gridy = 0;
        formPanel.add(createLabel("发货单ID:"), gbc);
        
        gbc.gridx = 1;
        shipmentIdField = createTextField();
        formPanel.add(shipmentIdField, gbc);
        
        gbc.gridx = 2;
        formPanel.add(createLabel("发货单号:"), gbc);
        
        gbc.gridx = 3;
        shipmentNumberField = createTextField();
        formPanel.add(shipmentNumberField, gbc);
        
        // 第二行
        gbc.gridx = 0;
        gbc.gridy = 1;
        formPanel.add(createLabel("关联订单ID:"), gbc);
        
        gbc.gridx = 1;
        orderIdField = createTextField();
        formPanel.add(orderIdField, gbc);
        
        gbc.gridx = 2;
        formPanel.add(createLabel("发货仓库ID:"), gbc);
        
        gbc.gridx = 3;
        warehouseIdField = createTextField();
        formPanel.add(warehouseIdField, gbc);
        
        // 第三行
        gbc.gridx = 0;
        gbc.gridy = 2;
        formPanel.add(createLabel("发货日期从:"), gbc);
        
        gbc.gridx = 1;
        startDateField = createTextField();
        startDateField.setToolTipText("格式: yyyy-MM-dd");
        formPanel.add(startDateField, gbc);
        
        gbc.gridx = 2;
        formPanel.add(createLabel("发货日期至:"), gbc);
        
        gbc.gridx = 3;
        endDateField = createTextField();
        endDateField.setToolTipText("格式: yyyy-MM-dd");
        formPanel.add(endDateField, gbc);
        
        // 第四行
        gbc.gridx = 0;
        gbc.gridy = 3;
        formPanel.add(createLabel("承运商:"), gbc);
        
        gbc.gridx = 1;
        carrierField = createTextField();
        formPanel.add(carrierField, gbc);
        
        gbc.gridx = 2;
        formPanel.add(createLabel("物流单号:"), gbc);
        
        gbc.gridx = 3;
        trackingNumberField = createTextField();
        formPanel.add(trackingNumberField, gbc);
        
        // 第五行
        gbc.gridx = 0;
        gbc.gridy = 4;
        formPanel.add(createLabel("运输方式:"), gbc);
        
        gbc.gridx = 1;
        shippingMethodCombo = new JComboBox<>(new String[]{"", "空运", "海运", "陆运", "快递"});
        shippingMethodCombo.setFont(new Font("微软雅黑", Font.PLAIN, 14));
        formPanel.add(shippingMethodCombo, gbc);
        
        gbc.gridx = 2;
        formPanel.add(createLabel("状态:"), gbc);
        
        gbc.gridx = 3;
        statusCombo = new JComboBox<>(new String[]{"", "待发货", "已发货", "运输中", "已签收", "已取消"});
        statusCombo.setFont(new Font("微软雅黑", Font.PLAIN, 14));
        formPanel.add(statusCombo, gbc);
        
        // 第六行
        gbc.gridx = 0;
        gbc.gridy = 5;
        formPanel.add(createLabel("备注:"), gbc);
        
        gbc.gridx = 1;
        gbc.gridwidth = 3;
        notesField = createTextField();
        formPanel.add(notesField, gbc);
        
        // 按钮面板
        JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.CENTER, 20, 10));
        buttonPanel.setOpaque(false);
        
        JButton searchButton = new JButton("搜索");
        searchButton.setFont(new Font("微软雅黑", Font.BOLD, 14));
        searchButton.setBackground(SEARCH_BUTTON_COLOR);
        searchButton.setForeground(Color.WHITE);
        searchButton.setPreferredSize(new Dimension(100, 35));
        searchButton.setFocusPainted(false);
        searchButton.setBorderPainted(false);
        searchButton.setCursor(new Cursor(Cursor.HAND_CURSOR));
        
        JButton resetButton = new JButton("重置");
        resetButton.setFont(new Font("微软雅黑", Font.BOLD, 14));
        resetButton.setBackground(RESET_BUTTON_COLOR);
        resetButton.setForeground(Color.WHITE);
        resetButton.setPreferredSize(new Dimension(100, 35));
        resetButton.setFocusPainted(false);
        resetButton.setBorderPainted(false);
        resetButton.setCursor(new Cursor(Cursor.HAND_CURSOR));
        
        buttonPanel.add(searchButton);
        buttonPanel.add(resetButton);
        
        // 添加搜索按钮事件
        searchButton.addActionListener(e -> performSearch());
        
        // 添加重置按钮事件
        resetButton.addActionListener(e -> resetForm());
        
        // 组装查询面板
        panel.add(formPanel, BorderLayout.CENTER);
        panel.add(buttonPanel, BorderLayout.SOUTH);
        
        return panel;
    }
    
    /**
     * 创建标签
     */
    private JLabel createLabel(String text) {
        JLabel label = new JLabel(text);
        label.setFont(new Font("微软雅黑", Font.BOLD, 14));
        return label;
    }
    
    /**
     * 创建文本框
     */
    private JTextField createTextField() {
        JTextField textField = new JTextField();
        textField.setFont(new Font("微软雅黑", Font.PLAIN, 14));
        textField.setPreferredSize(new Dimension(150, 30));
        return textField;
    }
    
    /**
     * 创建表格面板
     */
    private JScrollPane createTablePanel() {
        // 创建表格模型
        String[] columnNames = {"发货单ID", "发货单号", "关联订单ID", "仓库ID", "发货日期", "承运商", "物流单号", "运输方式", "状态", "备注"};
        tableModel = new DefaultTableModel(columnNames, 0) {
            @Override
            public boolean isCellEditable(int row, int column) {
                return false;
            }
        };
        
        // 创建表格
        resultTable = new JTable(tableModel);
        resultTable.setRowHeight(30);
        resultTable.setFont(new Font("微软雅黑", Font.PLAIN, 14));
        resultTable.getTableHeader().setFont(new Font("微软雅黑", Font.BOLD, 14));
        resultTable.getTableHeader().setBackground(HEADER_COLOR);
        resultTable.getTableHeader().setForeground(Color.BLACK);
        resultTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        resultTable.setShowGrid(true);
        resultTable.setGridColor(new Color(230, 230, 230));
        
        // 设置表格内容居中
        DefaultTableCellRenderer centerRenderer = new DefaultTableCellRenderer();
        centerRenderer.setHorizontalAlignment(JLabel.CENTER);
        for (int i = 0; i < resultTable.getColumnCount(); i++) {
            resultTable.getColumnModel().getColumn(i).setCellRenderer(centerRenderer);
        }
        
        // 添加双击事件
        resultTable.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                if (e.getClickCount() == 2) {
                    selectShipment();
                }
            }
        });
        
        JScrollPane scrollPane = new JScrollPane(resultTable);
        scrollPane.setBorder(BorderFactory.createLineBorder(new Color(200, 200, 200)));
        
        return scrollPane;
    }
    
    /**
     * 创建底部按钮面板
     */
    private JPanel createButtonPanel() {
        JPanel panel = new JPanel(new FlowLayout(FlowLayout.CENTER, 20, 15));
        panel.setOpaque(false);
        
        selectButton = new JButton("选择");
        selectButton.setFont(new Font("微软雅黑", Font.BOLD, 14));
        selectButton.setBackground(BUTTON_COLOR);
        selectButton.setForeground(Color.WHITE);
        selectButton.setPreferredSize(new Dimension(120, 40));
        selectButton.setFocusPainted(false);
        selectButton.setBorderPainted(false);
        selectButton.setCursor(new Cursor(Cursor.HAND_CURSOR));
        
        cancelButton = new JButton("取消");
        cancelButton.setFont(new Font("微软雅黑", Font.BOLD, 14));
        cancelButton.setBackground(new Color(231, 76, 60));
        cancelButton.setForeground(Color.WHITE);
        cancelButton.setPreferredSize(new Dimension(120, 40));
        cancelButton.setFocusPainted(false);
        cancelButton.setBorderPainted(false);
        cancelButton.setCursor(new Cursor(Cursor.HAND_CURSOR));
        
        panel.add(selectButton);
        panel.add(cancelButton);
        
        // 添加按钮事件
        selectButton.addActionListener(e -> selectShipment());
        cancelButton.addActionListener(e -> dispose());
        
        return panel;
    }
    
    /**
     * 执行搜索
     */
    private void performSearch() {
        Map<String, Object> conditions = new HashMap<>();
        
        // 收集查询条件
        if (!shipmentIdField.getText().trim().isEmpty()) {
            try {
                int id = Integer.parseInt(shipmentIdField.getText().trim());
                conditions.put("shipmentId", id);
            } catch (NumberFormatException e) {
                JOptionPane.showMessageDialog(this, "发货单ID必须是数字", "输入错误", JOptionPane.ERROR_MESSAGE);
                return;
            }
        }
        
        if (!shipmentNumberField.getText().trim().isEmpty()) {
            conditions.put("shipmentNumber", shipmentNumberField.getText().trim());
        }
        
        if (!orderIdField.getText().trim().isEmpty()) {
            try {
                int orderId = Integer.parseInt(orderIdField.getText().trim());
                conditions.put("orderId", orderId);
            } catch (NumberFormatException e) {
                JOptionPane.showMessageDialog(this, "订单ID必须是数字", "输入错误", JOptionPane.ERROR_MESSAGE);
                return;
            }
        }
        
        if (!warehouseIdField.getText().trim().isEmpty()) {
            try {
                int warehouseId = Integer.parseInt(warehouseIdField.getText().trim());
                conditions.put("warehouseId", warehouseId);
            } catch (NumberFormatException e) {
                JOptionPane.showMessageDialog(this, "仓库ID必须是数字", "输入错误", JOptionPane.ERROR_MESSAGE);
                return;
            }
        }
        
        // 处理日期范围
        if (!startDateField.getText().trim().isEmpty()) {
            try {
                LocalDate.parse(startDateField.getText().trim(), DATE_FORMATTER);
                conditions.put("shipDateFrom", startDateField.getText().trim());
            } catch (DateTimeParseException e) {
                JOptionPane.showMessageDialog(this, "开始日期格式错误，请使用yyyy-MM-dd格式", "输入错误", JOptionPane.ERROR_MESSAGE);
                return;
            }
        }
        
        if (!endDateField.getText().trim().isEmpty()) {
            try {
                LocalDate.parse(endDateField.getText().trim(), DATE_FORMATTER);
                conditions.put("shipDateTo", endDateField.getText().trim());
            } catch (DateTimeParseException e) {
                JOptionPane.showMessageDialog(this, "结束日期格式错误，请使用yyyy-MM-dd格式", "输入错误", JOptionPane.ERROR_MESSAGE);
                return;
            }
        }
        
        if (!carrierField.getText().trim().isEmpty()) {
            conditions.put("carrier", carrierField.getText().trim());
        }
        
        if (!trackingNumberField.getText().trim().isEmpty()) {
            conditions.put("trackingNumber", trackingNumberField.getText().trim());
        }
        
        if (shippingMethodCombo.getSelectedIndex() > 0) {
            conditions.put("shippingMethod", shippingMethodCombo.getSelectedItem().toString());
        }
        
        if (statusCombo.getSelectedIndex() > 0) {
            conditions.put("status", statusCombo.getSelectedItem().toString());
        }
        
        if (!notesField.getText().trim().isEmpty()) {
            conditions.put("notes", notesField.getText().trim());
        }
        
        // 检查是否有查询条件
        if (conditions.isEmpty()) {
            JOptionPane.showMessageDialog(this, "请至少输入一个查询条件", "提示", JOptionPane.INFORMATION_MESSAGE);
            return;
        }
        
        try {
            // 执行高级查询
            List<SalesShipments> results = SelectSalesShipment.advancedSearchWithMap(conditions);
            updateTable(results);
        } catch (Exception e) {
            e.printStackTrace();
            JOptionPane.showMessageDialog(this, "查询过程中发生错误：" + e.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
        }
    }
    
    /**
     * 重置表单
     */
    private void resetForm() {
        shipmentIdField.setText("");
        shipmentNumberField.setText("");
        orderIdField.setText("");
        warehouseIdField.setText("");
        startDateField.setText("");
        endDateField.setText("");
        carrierField.setText("");
        trackingNumberField.setText("");
        shippingMethodCombo.setSelectedIndex(0);
        statusCombo.setSelectedIndex(0);
        notesField.setText("");
        
        // 清空表格
        tableModel.setRowCount(0);
    }
    
    /**
     * 更新表格数据
     */
    private void updateTable(List<SalesShipments> shipments) {
        // 清空表格
        tableModel.setRowCount(0);
        
        if (shipments == null || shipments.isEmpty()) {
            JOptionPane.showMessageDialog(this, "未找到匹配的记录", "提示", JOptionPane.INFORMATION_MESSAGE);
            return;
        }
        
        // 填充表格
        for (SalesShipments shipment : shipments) {
            String dateStr = shipment.getShipmentDate() != null ? 
                shipment.getShipmentDate().format(DATE_FORMATTER) : "";
            
            Object[] rowData = {
                shipment.getShipmentId(),
                shipment.getShipmentNumber(),
                shipment.getOrderId(),
                shipment.getWarehouseId(),
                dateStr,
                shipment.getCarrier(),
                shipment.getTrackingNumber(),
                shipment.getShippingMethod(),
                shipment.getStatus(),
                shipment.getNotes()
            };
            
            tableModel.addRow(rowData);
        }
    }
    
    /**
     * 选择发货单
     */
    private void selectShipment() {
        int selectedRow = resultTable.getSelectedRow();
        
        if (selectedRow == -1) {
            JOptionPane.showMessageDialog(this, "请选择一条记录", "提示", JOptionPane.INFORMATION_MESSAGE);
            return;
        }
        
        int id = (int) tableModel.getValueAt(selectedRow, 0);
        
        // 获取选中的发货单
        List<SalesShipments> shipments = SelectSalesShipment.selectById(id);
        
        if (shipments != null && !shipments.isEmpty()) {
            selectedShipment = shipments.get(0);
            confirmed = true;
            
            // 更新主表格
            if (mainTable != null) {
                SalesShipmentsManagement.updateTableData(mainTable, shipments);
                MainView.updateStatusMessage("已选择发货单ID: " + id);
            }
            
            dispose();
        }
    }
    
    /**
     * 判断是否确认选择
     */
    public boolean isConfirmed() {
        return confirmed;
    }
    
    /**
     * 获取选中的发货单
     */
    public SalesShipments getSelectedShipment() {
        return selectedShipment;
    }
    
    /**
     * 主方法（用于测试）
     */
    public static void main(String[] args) {
        try {
            UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
        } catch (Exception e) {
            e.printStackTrace();
        }
        
        SwingUtilities.invokeLater(() -> {
            AdvancedSearchSalesShipmentDialog dialog = new AdvancedSearchSalesShipmentDialog(null, null);
            dialog.setVisible(true);
        });
    }
} 